package com.ftg.learn.student.util;

import com.ftg.learn.student.mapper.StudentMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;

/**
 * javabase基于纯java配置mybatis : xml
 * @author kangjx
 * @createTime 2022/7/29
 */
public class BaseSession<T> {

    private  static SqlSession session;


    static{
        //配置文件
        String url = "jdbc:mysql://localhost:3306/cool2204?serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "Love0913@kjx";
        String driverClass = "com.mysql.cj.jdbc.Driver";


        //mybatis配置文件的顶级节点
        Configuration configuration = new Configuration();
        //xml - settings
        configuration.setCacheEnabled(true);
        configuration.setLazyLoadingEnabled(true);
        configuration.setLogImpl(StdOutImpl.class);

        //环境设置
        TransactionFactory tf = new JdbcTransactionFactory();
        DataSource dataSource = new PooledDataSource(driverClass, url, username, password);
        Environment e = new Environment("localMysql",tf,dataSource);
        configuration.setEnvironment(e);

        //把接口注入到configuration
        configuration.addMappers("com.ftg.learn.student.mapper");
//        configuration.setDefaultExecutorType(ExecutorType.BATCH);


        //mybatis ssfb  ssf ss
        SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
        SqlSessionFactory ssf = ssfb.build(configuration);

        session = ssf.openSession(true);
        session.getMapper(StudentMapper.class);
    }

    public static SqlSession getSession(){
        return session;
    }


    public T getBean(Class<T> t){
        return getSession().getMapper(t);
    }

}
